package com.bawei.product.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.bawei.product.domain.pojo.ProductClassifyPO;
import com.bawei.product.domain.vo.ProductClassifyVo;
import com.bawei.product.mapper.ProductClassifyMapper;
import com.bawei.product.service.ProductClassifyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProductClassifyServiceImpl implements ProductClassifyService {

    @Autowired
    private ProductClassifyMapper productClassifyMapper;
    @Override
    public List<ProductClassifyVo> getAll() {
        List<ProductClassifyPO> classifyPos = productClassifyMapper.getAll();
        log.info("classifyPos:{}", JSONObject.toJSONString(classifyPos));
        Map<Integer, List<ProductClassifyVo>> map = new HashMap<>();

        // 将 ProductClassifyPO 转换为 ProductClassifyVo
        List<ProductClassifyVo> classifyVos = classifyPos.stream()
                .map(this::convertToVo)
                .collect(Collectors.toList());

        // 构建树形结构
        for (ProductClassifyVo classifyVo : classifyVos) {
            if (classifyVo.getParentId() != null && classifyVo.getParentId() != 0) {
                map.computeIfAbsent(classifyVo.getParentId(), k -> new ArrayList<>()).add(classifyVo);
            }
        }

        // 递归设置子集
        classifyVos.forEach(classifyVo -> setChildren(classifyVo, map));

        // 返回根节点分类
        return classifyVos.stream()
                .filter(classifyVo -> classifyVo.getParentId() == 0)
                .collect(Collectors.toList());
    }

    private ProductClassifyVo convertToVo(ProductClassifyPO classifyPO) {
        ProductClassifyVo classifyVo = new ProductClassifyVo();
        classifyVo.setId(classifyPO.getId());
        classifyVo.setClassifyName(classifyPO.getClassifyName());
        classifyVo.setParentId(classifyPO.getParentId());
        return classifyVo;
    }

    private void setChildren(ProductClassifyVo classifyVo, Map<Integer, List<ProductClassifyVo>> map) {
        List<ProductClassifyVo> children = map.get(classifyVo.getId());
        if (children != null) {
            classifyVo.setChildren(children);
            for (ProductClassifyVo child : children) {
                setChildren(child, map);
            }
        }
    }

}
